package com.atguigu.cart.interceptor;

import com.atguigu.cart.to.UserInfoTo;
import com.atguigu.common.to.AutoLoginResponse;
import com.atguigu.common.to.UmsMemberEntity;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {

    //使用ThreadLocal来封装UserInfoTo
    public static ThreadLocal<UserInfoTo> local = new ThreadLocal();



    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //封装对象给控制层
        UserInfoTo infoTo = new UserInfoTo();
        UmsMemberEntity umsMemberEntity = (UmsMemberEntity) request.getSession().getAttribute(AutoLoginResponse.REDIS_SESSION_LOGIN);
        //判断是否登录
        if (umsMemberEntity != null) {
            infoTo.setUserId(umsMemberEntity.getId());
        }

        //遍历coookie看是否存在对应的user-key
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("user-key".equals(cookie.getName())) {
                    //说明存在对应的cookie信息
                    infoTo.setUserKey(cookie.getValue());
                    infoTo.setTempUser(true);
                }

            }
        }


        //如果不存在对应的user-key，设置并且给浏览器响应
        if (infoTo.getUserKey() == null) {
            String uuid = UUID.randomUUID().toString();
            infoTo.setUserKey(uuid);
        }
        //放入thyreadLocal中，为了同一线程的数据共享
        local.set(infoTo);
        return true;
    }


    /**
     * 执行目标方法之后
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //与登录无关-如果user-key不存在，给浏览器响应
        UserInfoTo infoTo = local.get();

        //获取user-key给浏览器缓存
        if (!infoTo.isTempUser()) {
            Cookie cookie = new Cookie("user-key", infoTo.getUserKey());
            cookie.setDomain("gulimail.com");
            cookie.setMaxAge(60*60*24*30);

            response.addCookie(cookie);
        }
        //移除threadlocal
        local.remove();

    }
}
